package com.wanhe.soserver;

import android.support.annotation.Keep;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * 配置PAD端本地的socket服务端配置属性信息
 * <p>
 * <p>
 * Created by cdj on 2017/3/14.
 */
@Keep
public class ServerConfig {

    private String IP;
    private int port;
    private IKeyGenerator mKeyGenerator;
    private String mSecretKey;
    private long mClientHeartBitTime;   //心跳间隔，超过间隔意味着断开连接

    /**
     * 初始化配置信息
     *
     * @author 陈德基
     * @time 2017/3/14 9:38
     */
    public static ServerConfig config() {
        return new ServerConfig();
    }

    private ServerConfig() {
        this.IP = getLocalIpAddress();
        setSecretKeyGenerator(new BaseKeyGenerator());
    }

    public ServerConfig setPort(int port) {
        this.port = port;
        return this;
    }

    public ServerConfig setSecretKeyGenerator(IKeyGenerator generator) {
        this.mKeyGenerator = generator;
        this.mSecretKey = mKeyGenerator.generatKey();
        return this;
    }

    public String getSecretKey() throws NotInitializeKeyGenerator {
        if (mSecretKey == null)
            throw new NotInitializeKeyGenerator();
        return this.mSecretKey;
    }

    public ServerConfig setHeartBitTimeOut(long millse){
        this.mClientHeartBitTime = millse;
        return this;
    }

    public int getPort() {
        return this.port;
    }

    //获取本地IP
    public static String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            ex.printStackTrace();
        }
        return null;
    }

}
